package com.xw.wuliu;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.BMapManager;
import com.baidu.mapapi.map.LocationData;
import com.baidu.mapapi.map.MKMapViewListener;
import com.baidu.mapapi.map.MapController;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MyLocationOverlay;
import com.baidu.platform.comapi.basestruct.GeoPoint;
import com.xw.service.LocationTrackerSvc;

/**
 * 
 * 
 * 
 * @author gxw 功能：显示百度地图,GPS定位，工具栏（我的位置、公交搜索按钮）
 * 
 */

public class MapSignInActivity extends Activity {

	int i = 0;
	private LocationClient mLocClient; // 定位客户端

	public MyLocationListenner myListener = new MyLocationListenner();// 定位监听，获取位置时会回调成员函数。

	public MKMapViewListener mMapListener = null; // 监听MAP视图事件,例如单击等.
	MyLocationOverlay myLocationOverlay = null; // 位置图层

	LocationData locData = null;
	private MapController mMapController = null; // 控制器，控制地图大小等属性。
	private ImageButton imgbt_mypos = null;
	private ImageButton imgbt_signIn = null;
	private ImageButton imgbt_feedback = null;
	
	private String city = "";
	private String streetName = "";
	private String doorNo = ""; // 门牌号

	private Handler mHandler = null;

	int lat = 0; // 纬度
	int lng = 0; // 经度

	MapView mMapView = null; // 地图View

	DemoApplication app = null;

	private ListView lvOrder = null; // 服务单



	public List<String> getData() {

		List<String> data = new ArrayList<String>();
		data.add("服务单1");
		data.add("服务单2");
		data.add("服务单3");
		data.add("服务单4");
		return data;
	}

	/**
	 * 功能：初始化基本控件 参数：无 返回值：无
	 * 
	 */
	public void setupView()
	{
		
		setTitle("版权所有，违者必究，高小伟");
		
		mHandler = 	new Handler() {
	        public void handleMessage(android.os.Message msg) {
	            
	        };
	    };
		
	    lvOrder = (ListView) findViewById(R.id.lvOrder);
	    lvOrder.setOnItemClickListener(new OnItemClickListener()
	    {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int position,long arg3) {
				
				      //进入反馈表单的填写和提交
				        Intent feedback = new Intent();
				        feedback.setClass(MapSignInActivity.this, FeedBackForm.class);
				        startActivity(feedback);

			}
	    	
	    });
	    		
	    
	    
		//启动查询配置页面
	    imgbt_feedback = (ImageButton) findViewById(R.id.imgbt_feedback);
	    
	    imgbt_feedback.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v) {
				
				if(lvOrder.getVisibility() == View.GONE)
				{
					ArrayAdapter adapter0  = new ArrayAdapter(MapSignInActivity.this, 
							android.R.layout.simple_expandable_list_item_1, getData());
					
					lvOrder.setAdapter(adapter0);
					lvOrder.setVisibility(View.VISIBLE);

				}
				else
				{
					lvOrder.setVisibility(View.GONE);

				}

			}
		});
		
		
		//“我的位置”按钮，实时获取当前位置.
	    imgbt_signIn = (ImageButton) findViewById(R.id.imgbt_signIn);
	    imgbt_signIn.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v) {

		        int ret = mLocClient.requestLocation();
		        Log.i("myLoc","requestLoc return="+ret);
		        Toast.makeText(MapSignInActivity.this, "已签到", Toast.LENGTH_LONG).show();
			}
		});
	    
	    
		//“我的位置”按钮，实时获取当前位置.
	    imgbt_mypos = (ImageButton) findViewById(R.id.imgbt_mypos);
	    imgbt_mypos.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v) {

		        int ret = mLocClient.requestLocation();
		        Log.i("myPos","requestLoc return="+ret);
			}
		});
	    
	    
	    		
		//地图控件
        mMapView = (MapView)findViewById(R.id.bmapView);
        
        //初始化地图
        initMapView();
	}

	/**
	 * 功能：验证地图key是否合法 参数：无 返回值：无
	 * 
	 */
	void InitAppMapKey() {

		DemoApplication app = (DemoApplication) this.getApplication();
		if (app.mBMapManager == null) {

			app.mBMapManager = new BMapManager(this);

			app.mBMapManager.init(DemoApplication.strKey,
					new DemoApplication.MyGeneralListener());
		}
	}

	/**
	 * 功能：初始化定位器，并启动位置变化监听器 参数：无 返回值：无
	 * 
	 */
	void InitLocationClient() {
		
		mLocClient = new LocationClient(this);
		configLocClient();
	}
	
	
	public  void startLocClient()
	{		
		    mLocClient.registerLocationListener(myListener);
	        mLocClient.start();
	}
	
	public void configLocClient()
	{
		// 配置定位选项
		LocationClientOption option = new LocationClientOption();
		option.setOpenGps(true); // 启用gps芯片定位
		option.setAddrType("all");
		option.setCoorType("bd09ll"); // 设置坐标类型为百度坐标
		option.setScanSpan(30000); // 每隔获取一次最新经纬度
		mLocClient.setLocOption(option);
		
	}
	
	public void cancelLocationClient()
	{
		mLocClient.stop();
		mLocClient.unRegisterLocationListener(myListener);
		
	}

	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);

		// 验证MAP的key值
		InitAppMapKey();

		setContentView(R.layout.main_map);

		//初始化主要UI视图
		setupView();

		//初始化定位器客户端并开始搜索位置，即定位器。用于前台服务
		InitLocationClient();
		
		//启动后台位置服务
		//startLocBackSvc();
	}
	
	
	public void startLocBackSvc()
	{
		
		Intent i = new Intent();
		i.setAction("com.xw.locationsvc");
		this.startService(i);
		
	}
	
	public void stopLocBackService()
	{
		Intent i = new Intent();
		i.setAction("com.xw.locationsvc");
		this.stopService(i);
	}

	/**
	 * 功能：位置及POI信息监听，获取位置时或者搜索完周边POI信息时，调用回调函数
	 */
	public class MyLocationListenner implements BDLocationListener {

		// 获得位置时，回调此函数
		@Override
		public void onReceiveLocation(BDLocation location) {
			if (location == null)
				return;

			// 纬度、经度、精度、方向
			locData.latitude = location.getLatitude();
			locData.longitude = location.getLongitude();
			locData.accuracy = location.getRadius();
			
			String gpsType = "";
			
			// 街道门牌，城市名，省名
			if(location.getLocType() == 161 ) //如果这次是网络定位
			{
				String street = location.getStreet();
				String cityName = location.getCity();
				String province = location.getProvince();
	
				gpsType ="网络定位";
				city = cityName;
				streetName = street;
				Log.i("location", "add:" +i+ street);
			}
			else if(location.getLocType() == 61)
			{
				
				locData.direction = location.getDerect(); //方向
				gpsType ="GPS定位";
				
			}
			else
			{
				gpsType = String.valueOf(location.getLocType());
			}

			i++;

			myLocationOverlay.setData(locData);
			mMapView.refresh();

			// 地图中心移动到当前位置
			mMapController.animateTo(new GeoPoint((int) (locData.latitude * 1e6),(int) (locData.longitude * 1e6)), mHandler.obtainMessage(1));
			
			//Toast.makeText(MapSignInActivity.this, "frontSvc"+gpsType+":"+locData.latitude+","+locData.longitude, Toast.LENGTH_LONG).show();
		}

		// 获得周边POI信息时，回调
		public void onReceivePoi(BDLocation poiLocation) {
			if (poiLocation == null) {
				return;
			}
		}
	}

	/**
	 * 功能：初始化百度地图
	 * 
	 */
	private void initMapView() {

		mMapController = mMapView.getController();
		mMapController.enableClick(true); // 可单击地图
		mMapController.setZoom(12); // 地图大小级别放到12
		mMapView.setBuiltInZoomControls(true); // 添加+-放大缩小按钮
		mMapView.setDoubleClickZooming(true); // 可双击放大
		mMapView.setLongClickable(true); // 可长按

		// 设置地图敲击事件监听器，在这里处理 地图上单击或MOVE事件
		mMapListener = new MapViewListener(lvOrder);
		mMapView.regMapViewListener(DemoApplication.getInstance().mBMapManager,
				mMapListener);

		// 初始化位置点图层
		myLocationOverlay = new MyLocationOverlay(mMapView);
		locData = new LocationData();
		myLocationOverlay.setData(locData);

		myLocationOverlay.enableCompass(); // 开启指南针，GPS芯片定位时起效
		mMapView.getOverlays().add(myLocationOverlay);

		mMapView.refresh();

	}

	/**
	 * 功能：Activity页面销毁时，调用此互调函数，释放地图管理器
	 * 
	 */
	@Override
	protected void onDestroy() {
		
		if(mMapView!=null)
		{
			mMapView.destroy();
			mMapView = null;
		}
		
		DemoApplication app = (DemoApplication) this.getApplication();
		if (app.mBMapManager != null) {
			app.mBMapManager.destroy();
			app.mBMapManager = null;
		}
		
		//stopLocBackService();

		super.onDestroy();
	}

	/**
	 * 功能：Activity隐藏或被其他页面挡住时，调用此互调函数，暂停地图加载
	 * 
	 */
	@Override
	protected void onPause() {
		mMapView.onPause();
		cancelLocationClient();//gxw+
		super.onPause();
	}

	/**
	 * 功能：Activity重新显示在前台时，调用此互调函数，恢复地图的显示和加载
	 * 
	 */
	@Override
	protected void onResume() {
		mMapView.onResume();
		
		if(!mLocClient.isStarted())
			startLocClient(); //gxw+
		super.onResume();
	}

	/**
	 * 功能：保存百度地图的状态
	 * 
	 */
	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		mMapView.onSaveInstanceState(outState);

	}

	/**
	 * 功能：恢复百度地图的状态
	 * 
	 */
	@Override
	protected void onRestoreInstanceState(Bundle savedInstanceState) {
		super.onRestoreInstanceState(savedInstanceState);
		mMapView.onRestoreInstanceState(savedInstanceState);
	}

}
